/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import _entity.CartItem;
import common.DBConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateful;

/**
 *
 * @author HP
 */
@Stateful
public class ShoppingCart implements ShoppingCartRemote {

    private List<CartItem> items = new ArrayList<CartItem>();

    @Override
    public int add(CartItem item) {
        item.setQuantity(item.getQuantity() <= 0 ? 1 : item.getQuantity());
        for (CartItem i : items) {
            if (i.equals(item)) {
                i.setQuantity(i.getQuantity() + item.getQuantity());
                return 1;
            }
        }

        items.add(item);

        return 1;
    }

    @Override
    public int update(CartItem item) {
        if (item.getQuantity() <= 0) {
            remove(item);
            return 1;
        }

        for (CartItem i : items) {
            if (i.equals(item)) {
                i.setQuantity(item.getQuantity());

                return 1;
            }
        }
        return 0;
    }

    @Override
    public int remove(CartItem item) {
        for (CartItem i : items) {
            if (i.equals(item)) {
                items.remove(i);

                return 1;
            }
        }
        return 0;
    }

    @Override
    public CartItem get(int productID) {
        for (CartItem i : items) {
            if (i.getProduct().getId() == productID) {
                return i;
            }
        }
        return null;
    }

    @Override
    public int count() {
        return items.size();
    }

    @Override
    public List<CartItem> getAll() {
        return items;
    }

    @Override
    public int saveShoppingCart() {
        int result = 0;

        if (items.isEmpty()) {
            return 0;
        }

        Connection cnn = DBConnection.getConnection();
        if (cnn != null) {
            try {
                double totalAmount = getTotalAmount();
                int ordersID = -1;

                String SQL_ORDERS = String.format("INSERT INTO orders(totalAmount) values(%s)", totalAmount);
                String SQL_ORDERSDETAILS = "INSERT INTO ordersDetails(ordersID, productID, quantity, currentPrice) values(?, ?, ?, ?)";

                Statement st = cnn.createStatement();
                result = st.executeUpdate(SQL_ORDERS, Statement.RETURN_GENERATED_KEYS);
                ResultSet rs = st.getGeneratedKeys();
                if (rs.next()) {
                    ordersID = rs.getInt(1);
                } else {
                    throw new SQLException("Can't insert orders into DB");
                }

                PreparedStatement psOrdersDetails = cnn.prepareStatement(SQL_ORDERSDETAILS);
                for (CartItem item : items) {

                    psOrdersDetails.setInt(1, ordersID);
                    psOrdersDetails.setInt(2, item.getProduct().getId());
                    psOrdersDetails.setInt(3, item.getQuantity());
                    psOrdersDetails.setDouble(4, item.getProduct().getPrice().doubleValue());

                    psOrdersDetails.executeUpdate();
                }

            } catch (SQLException ex) {
                try {
                    cnn.rollback();
                } catch (SQLException ex1) {
                    Logger.getLogger(ShoppingCart.class.getName()).log(Level.SEVERE, null, ex1);
                }
                Logger.getLogger(ShoppingCart.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        return result;
    }

    @Override
    public double getTotalAmount() {
        double result = 0.0;

        for (CartItem item : items) {
            result += item.getProduct().getPrice().doubleValue() * item.getQuantity();
        }

        return result;
    }
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
}
